package com.example.controller;

import com.example.entity.*;
import com.example.entity.bo.CourseStudentResultBO;
import com.example.entity.bo.StudentCourseResultBO;
import com.example.entity.example.CourseExample;
import com.example.entity.example.TeacherExample;
import com.example.entity.vo.LectureVO;
import com.example.security.SecurityUser;
import com.example.service.*;
import com.example.util.CustomUtil;
import com.example.util.ResultEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RequestMapping("/lecture")
@Controller
public class LectureController {
    @Autowired
    LectureService lectureService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    CourseService courseService;

    @Autowired
    StudentService studentService;

    @Autowired
    CourseSelectionResultService courseSelectionResultService;

    public LectureVO transformToLectureVO(Lecture lecture) {
        LectureVO lectureVO = new LectureVO();
        BeanUtils.copyProperties(lecture, lectureVO);

        String teacherId = lecture.getTeacherId();
        Teacher teacher = teacherService.getById(teacherId);
        if (teacher != null) {
            lectureVO.setTeacherName(teacher.getName());
        }

        String courseId = lecture.getCourseId();
        Course course = courseService.getById(courseId);
        if (course != null) {
            lectureVO.setCourseName(course.getName());
        }

        return lectureVO;
    }

    @PreAuthorize("hasRole('ROLE_管理员') or hasRole('ROLE_教师')")
    @ResponseBody
    @RequestMapping("/get.json")
    public ResultEntity<List<LectureVO>> get(@RequestParam("page") Integer page,
                                             @RequestParam("limit") Integer limit,
                                             @RequestParam(value = "teacherName", required = false) String teacherName,
                                             @RequestParam(value = "courseName", required = false) String courseName,
                                             @RequestParam(value = "beginDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginDate,
                                             @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate,
                                             HttpSession session
    ) {
        User me = CustomUtil.getCurrentUser(session).getOriginalUser();
        String teacherId = "";
        if (!"管理员".equals(me.getRole())) {
            // 老师只能查看自己的课程
            teacherId = me.getBindId();
            teacherName = teacherService.getById(teacherId).getName();
        }
        if (teacherName != null) {
            if (teacherName.isEmpty()) {
                teacherName = null;
            } else {
                teacherName = '%' + teacherName + '%';
            }
        }
        if (courseName != null) {
            if (courseName.isEmpty()) {
                courseName = null;
            } else {
                courseName = '%' + courseName + '%';
            }
        }
        if (endDate != null) {
            // 将结束日期向后推迟一天
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            calendar.add(Calendar.DAY_OF_MONTH, 1);    // +1天
            endDate = calendar.getTime();
        }
        List<Lecture> lectures = lectureService.getByExampleWithLimit(teacherName, courseName, beginDate, endDate, page, limit);
        List<LectureVO> lectureVOs = new ArrayList<>(lectures.size());
        for (Lecture lecture : lectures) {
            if (teacherId.isEmpty() || teacherId.equals(lecture.getTeacherId())) {
                // 防止出现同名情况, 只有id相同才放入列表
                LectureVO lectureVO = this.transformToLectureVO(lecture);
                lectureVOs.add(lectureVO);
            }
        }
        long count = lectureService.getCountByExample(teacherName, courseName, beginDate, endDate);
        return ResultEntity.createResultEntity(0, null, count, lectureVOs);
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @RequestMapping("/add/page.html")
    public String addPage(ModelMap modelMap) {
        List<Teacher> teacherList = teacherService.getByExampleWithLimit(new TeacherExample(), 1, Integer.MAX_VALUE);
        List<Course> courseList = courseService.getByExampleWithLimit(new CourseExample(), 1, Integer.MAX_VALUE);
        modelMap.addAttribute("teacherList", teacherList);
        modelMap.addAttribute("courseList", courseList);
        return "lecture/lecture-add";
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("add")
    public ResultEntity<Object> add(@RequestBody Lecture lecture) {
        lectureService.add(lecture);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @RequestMapping("/{id}/modify/page.html")
    public String modifyPage(ModelMap modelMap, @PathVariable("id") Integer id) {
        Lecture lecture = lectureService.getById(id);
        Teacher teacher = teacherService.getById(lecture.getTeacherId());
        Course course = courseService.getById(lecture.getCourseId());
        List<Teacher> teacherList = teacherService.getByExampleWithLimit(new TeacherExample(), 1, Integer.MAX_VALUE);
        List<Course> courseList = courseService.getByExampleWithLimit(new CourseExample(), 1, Integer.MAX_VALUE);
        modelMap.addAttribute("lecture", lecture);
        modelMap.addAttribute("teacher", teacher);
        modelMap.addAttribute("course", course);
        modelMap.addAttribute("teacherList", teacherList);
        modelMap.addAttribute("courseList", courseList);
        return "lecture/lecture-modify";
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/update")
    public ResultEntity<Object> update(@RequestBody Lecture lecture) {
        lectureService.updateById(lecture);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/remove")
    public ResultEntity<Object> remove(@RequestParam("id") Integer id) {
        lectureService.removeById(id);
        return ResultEntity.successWithoutData();
    }


    /**
     * 前往教师录入成绩页面
     */
    @PreAuthorize("hasRole('ROLE_教师')")
    @RequestMapping("/course/results/page.html")
    public String courseResultsPage(ModelMap modelMap, HttpSession session) {
        User me = CustomUtil.getCurrentUser(session).getOriginalUser();
        String teacherId = me.getBindId();
        List<Student> studentList = studentService.getByTeacherId(teacherId);
        List<Course> courseList = courseService.getByTeacherId(teacherId);
        modelMap.addAttribute("studentList", studentList);
        modelMap.addAttribute("courseList", courseList);
        modelMap.addAttribute("teacherId", teacherId);
        return "lecture/course-result-list";
    }

    /**
     * 获取某位教师的学生成绩
     */
    @PreAuthorize("hasRole('ROLE_教师') or hasRole('ROLE_管理员')")
    @ResponseBody
    @RequestMapping("/get/course/results.json")
    public ResultEntity<List<CourseStudentResultBO>> getCourseResults(@RequestParam("page") Integer page,
                                                                      @RequestParam("limit") Integer limit,
                                                                      @RequestParam(value = "teacherId", required = false) String teacherId,
                                                                      @RequestParam(value = "courseId", required = false) String courseId,
                                                                      @RequestParam(value = "studentId", required = false) String studentId,
                                                                      HttpSession session) {
        User me = CustomUtil.getCurrentUser(session).getOriginalUser();
        if (!"管理员".equals(me.getRole())) {
            // 老师只能查看自己学生的成绩
            teacherId = me.getBindId();
        }
        if (studentId == null || studentId.isEmpty()) {
            studentId = null;
        }
        if (courseId == null || courseId.isEmpty()) {
            courseId = null;
        }
        List<CourseStudentResultBO> courseList = lectureService.getCourseStudentResultsByExampleWithLimit(teacherId, courseId, studentId, page, limit);
        return ResultEntity.createResultEntity(0, null, (long) courseList.size(), courseList);
    }


    @PreAuthorize("hasRole('ROLE_教师') or hasRole('ROLE_管理员')")
    @RequestMapping("/update/courseResult")
    @ResponseBody
    public ResultEntity<Object> updateCourseResult(@RequestBody CourseStudentResultBO courseStudentResultBO) {
        CourseSelectionResult courseSelectionResult = new CourseSelectionResult();
        BeanUtils.copyProperties(courseStudentResultBO, courseSelectionResult);
        courseSelectionResultService.updateSelectiveById(courseSelectionResult);
        return ResultEntity.successWithoutData();
    }

    @PreAuthorize("hasRole('ROLE_教师') or hasRole('ROLE_管理员')")
    @RequestMapping("/remove/courseResult")
    @ResponseBody
    public ResultEntity<Object> removeCourseResult(@Param("id") Integer id) {
        courseSelectionResultService.removeById(id);
        return ResultEntity.successWithoutData();
    }
}
